import 'package:flame/collisions.dart';
import 'package:flame/components.dart';
import 'package:hero_back/study/flutter_game_flame/day005/components/hero.dart';
import 'package:hero_back/study/flutter_game_flame/day005/manager/animation_bullet.dart';

import '../mixins/liveable.dart';

class Monster extends SpriteAnimationComponent with Liveable, HasGameRef,CollisionCallbacks {
  SpriteAnimation bulletSprite;
  HeroAttr monsterAttr;
  final Vector2 bulletSize;
  late Timer timer;
  late bool isLeft;

  Monster({
    required SpriteAnimation animation,
    required this.bulletSize,
    required Vector2 size,
    required Vector2 position,
    required this.bulletSprite,
    required this.monsterAttr,
    required this.isLeft,
  }) : super(
          animation: animation,
          size: size,
          position: position,
          anchor: Anchor.center,
        );

  @override
  void onDied() {
    removeFromParent();
  }

  @override
  void onMount() {
    super.onMount();
    timer.start();
  }

  @override
  void update(double dt) {
    super.update(dt);
    timer.update(dt);
  }

  @override
  void onRemove() {
    super.onRemove();
    timer.stop();
  }

  @override
  Future<void> onLoad() async {
    timer = Timer(3, onTick: addBullet, repeat: true);
    initPaint(lifePoint: monsterAttr.life);
    addHitbox();
  }

  void addHitbox(){
    ShapeHitbox hitbox = RectangleHitbox();
    hitbox.debugMode = true;
    add(hitbox);
  }

  @override
  void onCollision(Set<Vector2> intersectionPoints, PositionComponent other) {
    super.onCollision(intersectionPoints, other);
    if(other is AnimationBullet && other.type == BulletType.hero) {
      loss(other.monsterAttr);
    }
  }

  void addBullet() {
    AnimationBullet bullet = AnimationBullet(
      animation: bulletSprite,
      speed: monsterAttr.attackSpeed,
      maxRange: monsterAttr.attackRange,
      type: BulletType.monster,
      isLeft: isLeft,
      monsterAttr: monsterAttr,
    );
    bullet.size = bulletSize;
    bullet.anchor = Anchor.center;
    bullet.priority = 1;
    priority = 2;
    bullet.position = position - Vector2(0, size.y / 2);
    gameRef.add(bullet);
  }

  void move(Vector2 ds) {
    position.add(ds);
  }
}
